package com.lxxie.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lxxie.bean.LayUIResponse;
import com.lxxie.com.lxxie.service.SqlHistoryService;
import com.lxxie.enums.Platform;
import com.lxxie.util.DESUtil;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by xielx on 20/11/25 16:58
 */
@RestController
public class QueryController {
        private Logger log = LoggerFactory.getLogger(getClass());
        private ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 10, 1,
                TimeUnit.DAYS, new ArrayBlockingQueue<>(1024));

        @Autowired
        private RestTemplate restTemplate;
        @Autowired
        private SqlHistoryService sqlHistoryService;

        @RequestMapping("/listPlatform")
        public LayUIResponse listPlatform(@RequestParam(value = "sfmc", defaultValue = "") String sfmc) {
                List<Map<String, Object>> result = new ArrayList<>();
                for (Platform plat : Platform.values()) {
                        if (plat.getSfmc().contains(sfmc)) {
                                result.add(plat.toMap());
                        }
                }
                return LayUIResponse.success(result);
        }

        @RequestMapping("/queryColumn")
        public LayUIResponse queryColumn(@RequestParam(value = "sfdm", defaultValue = "xx") String sfdm,
                                         @RequestParam(value = "sql", defaultValue = "NONE") String sqlq,
                                         @RequestParam(value = "actionType", defaultValue = "duck") String actionType,
                                         @RequestParam("limit") String limit){
                if ("xx".equals(sfdm) || "NONE".equals(sqlq)||!"duck".equals(actionType)) {
                        return LayUIResponse.success(new ArrayList<>());
                }
                log.info("收到查询请求，共需要查询 {}个省份：{}", sfdm.split(",").length, sqlq);
                //sqlq = sqlq.toLowerCase(Locale.ROOT).trim();
                if (sqlq.toLowerCase(Locale.ROOT).startsWith("select")) {
                        LayUIResponse.fail("更新");
                }
                final String sql = sqlq.toLowerCase(Locale.ROOT).contains("rownum")||!sqlq.toLowerCase(Locale.ROOT).startsWith("select")
                    ?sqlq:("select * from(" + sqlq + ") where rownum<=" + limit);
                ResponseEntity<String> columnResp = restTemplate.postForEntity("http://t.122.gov.cn:9003/ris/zwt/testQuey", sql, String.class);
                if (columnResp.getStatusCodeValue() != 200) {
                        return LayUIResponse.fail("请求列名失败"+columnResp.getBody());
                }
                JSONObject column = JSON.parseObject(columnResp.getBody());
                if (column.getInteger("code") != 200) {
                        return LayUIResponse.fail("请求列名失败"+columnResp.getBody());
                }
                return LayUIResponse.success(column.getJSONArray("data"));
        }

        @RequestMapping("/query")
        public LayUIResponse query(@RequestParam(value = "sfdm", defaultValue = "xx") String sfdm,
                                   @RequestParam(value = "sql", defaultValue = "NONE") String sqlq,
                                   @RequestParam(value = "actionType", defaultValue = "duck") String actionType,
                                   @RequestParam("limit") String limit) {
                try {
                        if ("xx".equals(sfdm) || "NONE".equals(sqlq)) {
                                return LayUIResponse.success(new ArrayList<>());
                        }
                        log.info("收到查询请求，共需要查询 {}个省份：{}", sfdm.split(",").length, sqlq);
                        //sqlq = sqlq.toLowerCase(Locale.ROOT).trim();
                        final String sql = sqlq.toLowerCase().contains("rownum")||!sqlq.toLowerCase().startsWith("select")
                            ?sqlq:("select * from(" + sqlq + ") where rownum<=" + limit);
                        String encodeSql = new String(Base64.encodeBase64(DESUtil.encrypt(sql.getBytes())));
                        JSONObject json = new JSONObject();
                        json.put("sfdm", sfdm);
                        json.put("content", encodeSql);
                        json.put("type",actionType);
                        if (sqlq.startsWith("select")&&"lady".equals(actionType)) {
                                return LayUIResponse.fail("模式不对");
                        }else if ("duck".equals(actionType)&&(sqlq.startsWith("update")||sqlq.startsWith("delete"))) {
                                return LayUIResponse.fail("模式不对");
                        }
                        pool.execute(() -> sqlHistoryService.save(sql));
                        ResponseEntity<String> str = restTemplate.postForEntity("http://gab.122.gov.cn/ris/risinfo/queryProvince",
                                json.toString().getBytes("UTF-8"), String.class);
                        log.info("收到了部平台传回来的信息..");
                        if (!str.getStatusCode().is2xxSuccessful()) {
                                return LayUIResponse.fail("访问部平台失败：" + str.getBody());
                        }
                        JSONArray resp = JSON.parseArray(str.getBody());
                        //createSql(resp);
                        return LayUIResponse.success(resp);
                } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        return LayUIResponse.fail(e);
                }
        }

        private void createSql(JSONArray resp) {
                for (int i = 0; i < resp.size(); i++) {
                        JSONArray datas = resp.getJSONObject(0).getJSONArray("data");
                        for (int k = 0; k < datas.size(); k++) {
                                StringBuilder s1 =  new StringBuilder("insert into xx_table(");
                                StringBuilder s2 =  new StringBuilder("values(");
                                JSONObject data = datas.getJSONObject(k);
                                data.keySet().forEach(key->{
                                        s1.append(key).append(",");
                                        String val = data.getString(key);
                                        if (val.length()==19 &&val.charAt(4)=='-' && val.charAt(7)=='-') {
                                                s2.append(String.format("to_date('%s','yyyy-mm-dd hh24:mi:ss'),",val));
                                        }else {
                                                s2.append("'").append(val).append("',");
                                        }
                                });
                                System.out.println(s1.replace(s1.length()-1,s1.length(),")"));
                                System.out.println(s2.replace(s2.length()-1,s2.length(),");"));
                        }
                }
        }

        @RequestMapping("/querySqlHis")
        public LayUIResponse querySqlHis() {
                try {
                        return LayUIResponse.success(sqlHistoryService.querySqlHis());
                } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        return LayUIResponse.fail(e);
                }
        }

        @RequestMapping("/delSqlHis")
        public LayUIResponse delSqlHis(@RequestParam("xh") String xh){
                sqlHistoryService.delHis(xh);
                return LayUIResponse.success("成功");
        }

}
